import performance from "./performance/index";
import behavior from "./behavior/index";
import error from "./error/index";
import { setConfig } from "./config";
import { lazyReportBatch } from "./report";

window.__webEyeSDK__ = {
  version: "0.0.1",
};

// 针对Vue进行错误处理
export function install(Vue, options) {
  if (__webEyeSDK__.vue) {
    return;
  }
  __webEyeSDK__.vue = true;
  const handler = Vue.config.errorHandler;
  // 在 Vue 项目中, 通过Vue.config.errorHandler 对Vue的错误进行处理
  Vue.config.errorHandler = function (err, vm, info) {
    // 调用错误上报接口
    const reportData = {
      info,
      error: err.stack,
      subType: "vue",
      type: "error",
      statTime: window.performance.now(),
      pageUrl: window.location.href,
    };
    lazyReportBatch(reportData);
    if (handler) {
      handler.call(this, err, vm, info);
    }
  };
}

// 针对React进行错误处理
export function errorBoundary(err, info) {
  if (__webEyeSDK__.react) {
    return;
  }
  __webEyeSDK__.react = true;
  // 调用错误上报接口
  const reportData = {
    error: err.stack,
    info,
    subType: "react",
    type: "error",
    statTime: window.performance.now(),
    pageUrl: window.location.href,
  };
  lazyReportBatch(reportData);
}

export function init(options) {
  setConfig(options);
}

export default {
  install,
  errorBoundary,
  performance,
  behavior,
  error,
};
